package com.qfedu.micrograss.grass.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qfedu.api.point.feign.PointFeignService;
import com.qfedu.common.core.common.PageVO;
import com.qfedu.common.core.common.R;
import com.qfedu.common.core.entity.Grass;
import com.qfedu.common.core.entity.GrassLike;
import com.qfedu.common.core.utils.UserUtils;
import com.qfedu.common.redis.utils.RedisUtil;
import com.qfedu.micrograss.grass.mapper.GrassMapper;
import com.qfedu.micrograss.grass.param.GrassParam;
import com.qfedu.micrograss.grass.param.GrassSearchParam;
import com.qfedu.micrograss.grass.param.TodayLikeInfoParam;
import com.qfedu.micrograss.grass.service.GrassLikeService;
import com.qfedu.micrograss.grass.service.GrassService;
import com.qfedu.micrograss.grass.vo.GrassVO;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class GrassServiceImpl implements GrassService {
    @Resource
    private GrassMapper grassMapper;
    @Resource
    private PointFeignService pointFeignService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private GrassLikeService grassLikeService;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void addGrass(GrassParam grassParam) {
        Integer uid = UserUtils.getUid();
        Grass grass = new Grass();
        BeanUtils.copyProperties(grassParam, grass);
        String imgPath = String.join(",", grassParam.getImgList());
        //String imgPath=grassParam.getImgList().stream().collect(Collectors.joining(","));
        grass.setImgPath(imgPath);
        grass.setUid(uid);
        grassMapper.insert(grass);
        R r = pointFeignService.remoteAddPoint(2);


    }


    @Override
    public PageVO<GrassVO> grassPage(GrassSearchParam grassSearchParam) {
        Integer uid = UserUtils.getUid();
        Page<Grass> page = new Page(grassSearchParam.getPageNum(), grassSearchParam.getPageSize());
        page = grassMapper.selectPage(page, Wrappers.lambdaQuery(Grass.class)
                .eq(Grass::getCheckStatus, 1));
        List<Grass> records = page.getRecords();
        //查询登录用户对应的文章
        List<Integer> idlist = records.stream().map(grass -> grass.getId()).collect(Collectors.toList());
        List<GrassLike> grassLikes = grassLikeService.listByGrassIdsAndUid(idlist, uid);


        String key = String.format("likeNum:%s", DateUtil.format(new Date(), "yyyyMMdd"));
        System.out.println("line75:" + key);
        List<GrassVO> voList = records.stream().map(grass -> {
            GrassVO vo = new GrassVO();
            vo.setId(grass.getId());
            vo.setTitle(grass.getTitle());
            String[] split = grass.getImgPath().split(",");
            vo.setCoverImg(split[0]);
            //数据表中存的不是最新数据,实时的点赞来自数据表女的likeNum字段和redis中的当天点赞数
            Integer todayLikeNum = (Integer) redisUtil.getCacheMapValue(key, grass.getId().toString());
            vo.setLikeNum(todayLikeNum == null ? grass.getLikeNum() : grass.getLikeNum() + todayLikeNum);
            //查点赞记录是否包含当前id
            GrassLike findLike = grassLikes.stream().filter(grassLike -> grassLike.getGrassId().
                    equals(grass.getId())).findFirst().orElse(null);

            vo.setLikeFlag(findLike == null ? 0 : 1);


            return vo;
        }).collect(Collectors.toList());
        PageVO<GrassVO> pageVO = new PageVO<>();
        pageVO.setTotal(page.getTotal());
        pageVO.setDataList(voList);


        return pageVO;
    }

    @Transactional

    @Override
    public void updateGrassLikeNumTask() {
        //从redis中取头一天的点赞记录
        //做分批的批量更新
        String yesterday = DateUtil.format(DateUtil.yesterday(), "yyyyMMdd");

        Map<String, Object> cacheMap = redisUtil.getCacheMap("likeNum:" + yesterday);

        // 原逻辑代码

        List<TodayLikeInfoParam> list = new ArrayList<>();
        for (String key : cacheMap.keySet()) {
            TodayLikeInfoParam todayLikeInfoParam = new TodayLikeInfoParam();
            todayLikeInfoParam.setGrassId(Integer.valueOf(key));
            todayLikeInfoParam.setLikeNum((Integer) cacheMap.get(key));
            list.add(todayLikeInfoParam);
            if (list.size() == 100) {
                grassMapper.updateBatch(list);
                list = new ArrayList<>();
            }
        }
        if (list.size() > 0) {
            grassMapper.updateBatch(list);
        }


    }

    @Override
    public PageVO<GrassVO> grassPage(GrassSearchParam grassSearchParam) {
        Integer uid = UserUtils.getUid();
        Page<Grass> page = new Page(grassSearchParam.getPageNum(), grassSearchParam.getPageSize());
        page = grassMapper.selectPage(page, Wrappers.lambdaQuery(Grass.class)
                .eq(Grass::getCheckStatus, 1));
        List<Grass> records = page.getRecords();
        //查询登录用户对应的文章
        List<Integer> idlist = records.stream().map(grass -> grass.getId()).collect(Collectors.toList());
        List<GrassLike> grassLikes = grassLikeService.listByGrassIdsAndUid(idlist, uid);


        String key = String.format("likeNum:%s", DateUtil.format(new Date(), "yyyyMMdd"));
        System.out.println("line75:" + key);
        List<GrassVO> voList = records.stream().map(grass -> {
            GrassVO vo = new GrassVO();
            vo.setId(grass.getId());
            vo.setTitle(grass.getTitle());
            String[] split = grass.getImgPath().split(",");
            vo.setCoverImg(split[0]);
            //数据表中存的不是最新数据,实时的点赞来自数据表女的likeNum字段和redis中的当天点赞数
            Integer todayLikeNum = (Integer) redisUtil.getCacheMapValue(key, grass.getId().toString());
            vo.setLikeNum(todayLikeNum == null ? grass.getLikeNum() : grass.getLikeNum() + todayLikeNum);
            //查点赞记录是否包含当前id
            GrassLike findLike = grassLikes.stream().filter(grassLike -> grassLike.getGrassId().
                    equals(grass.getId())).findFirst().orElse(null);

            vo.setLikeFlag(findLike == null ? 0 : 1);


            return vo;
        }).collect(Collectors.toList());
        PageVO<GrassVO> pageVO = new PageVO<>();
        pageVO.setTotal(page.getTotal());
        pageVO.setDataList(voList);


        return pageVO;
    }

    @Transactional

    @Override
    public void updateGrassLikeNumTask() {
        //从redis中取头一天的点赞记录
        //做分批的批量更新
        String yesterday = DateUtil.format(DateUtil.yesterday(), "yyyyMMdd");

        Map<String, Object> cacheMap = redisUtil.getCacheMap("likeNum:" + yesterday);

        // 原逻辑代码

        List<TodayLikeInfoParam> list = new ArrayList<>();
        for (String key : cacheMap.keySet()) {
            TodayLikeInfoParam todayLikeInfoParam = new TodayLikeInfoParam();
            todayLikeInfoParam.setGrassId(Integer.valueOf(key));
            todayLikeInfoParam.setLikeNum((Integer) cacheMap.get(key));
            list.add(todayLikeInfoParam);
            if (list.size() == 100) {
                grassMapper.updateBatch(list);
                list = new ArrayList<>();
            }
        }
        if (list.size() > 0) {
            grassMapper.updateBatch(list);
        }


    }
}
